package uk.ac.ebi.dod.utils;

import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.Log;

import java.util.logging.Handler;
import java.util.logging.LogRecord;
import java.util.logging.Level;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


/**
 * @author Florian Reisinger
 * @since 0.1
 */
public class JDKLogHandler extends Handler {
    
        private Map<String, Log> cachedLogs = new ConcurrentHashMap<String, Log>();

        private Log getLog(String logName) {
                Log log = cachedLogs.get(logName);
                if (log == null) {
                        log = LogFactory.getLog(logName);
                        cachedLogs.put(logName, log);
                }
                return log;
        }

        @Override
        public void publish(LogRecord record) {
            Log log = getLog(record.getLoggerName());
            String message = record.getMessage();
            Throwable exception = record.getThrown();
            Level level = record.getLevel();
            if (level == Level.SEVERE) {
                log.error(message, exception);
            } else if (level == Level.WARNING) {
                log.warn(message, exception);
            } else if (level == Level.INFO) {
                log.info(message, exception);
            } else if (level == Level.CONFIG) {
                log.debug(message, exception);
            } else {
                log.trace(message, exception);
            }
        }

        @Override
        public void flush() {
                // nothing to do
        }

        @Override
        public void close() {
                // nothing to do
        }
}
